package cn.lingyangwl.agile.pay.client.manager;

import cn.lingyangwl.framework.core.utils.IpUtils;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import cn.lingyangwl.agile.pay.model.entity.RefundOrder;
import cn.lingyangwl.agile.pay.client.mapper.GoodsRefundMapper;
import cn.lingyangwl.agile.pay.client.model.rqrs.GoodsRefundRQ;
import cn.lingyangwl.agile.pay.client.model.entity.GoodsOrder;
import cn.lingyangwl.agile.pay.client.model.entity.GoodsRefund;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yitter.idgen.YitIdHelper;
import org.springframework.stereotype.Component;

/**
 * @author shenguangyang
 */
@Component
public class GoodsRefundManager extends ServiceImpl<GoodsRefundMapper, GoodsRefund> {
    /**
     * 更新退款中状态为其他
     */
    public void updateIngToOther(String mchRefundNo, GoodsRefund goodsRefund) {
        LambdaQueryWrapper<GoodsRefund> luq = GoodsRefund.lqw().eq(GoodsRefund::getMchRefundNo, mchRefundNo)
                .eq(GoodsRefund::getStatus, RefundOrder.STATE_ING);
        if (!this.update(goodsRefund, luq)) {
            throw new BizException("更新退款订单失败");
        }
    }

    public GoodsRefund saveGoodsRefund(GoodsRefundRQ req, GoodsOrder order) {
        String refundNo = String.valueOf(YitIdHelper.nextId());
        GoodsRefund goodsRefund = GoodsRefund.builder().goodsId(order.getGoodsId())
                .refundReason(req.getReason()).currency("cny")
                .payAmount(order.getPayAmount())
                .wayCode(order.getWayCode())
                .status(RefundOrder.STATE_ING).refundAmount(order.getPayAmount())
                .clientIp(IpUtils.getHostIp()).mchOrderNo(order.getMchOrderNo())
                .mchRefundNo(refundNo).build();
        if (!this.save(goodsRefund)) {
            throw new BizException("保存退款订单失败");
        }
        return goodsRefund;
    }
}
